﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Ideal.API.LinqTextQueryBuilder
{
    /// <summary>
    /// Used to generate Query class
    /// </summary>
    public class LinqTextQueryRuntimeProfiler
    {

        public LinqTextQueryRuntimeProfiler()
        {
            AddEntryAssemblyReferences = true;
        }

        public List<string> UsedAssembliesLocations { get; set; }
        public List<string> UsedNamespaces { get; set; }

        public bool AddEntryAssemblyReferences { get; set; }

        public void AddAssembly( Assembly assembly, bool withReferences = false )
        {
            AddAssembly( assembly.Location );
            if ( withReferences )
                AddAssemblyReferences( assembly );
        }
        public void AddAssembly( string assemblyLocation )
        {
            if ( UsedAssembliesLocations == null )
                UsedAssembliesLocations = new List<string>();
            UsedAssembliesLocations.Add( assemblyLocation );
        }
        public void AddNamespace( string ns )
        {
            if ( UsedNamespaces == null )
                UsedNamespaces = new List<string>();
            UsedNamespaces.Add( ns );
        }

        private void AddAssemblyReferences( Assembly assembly )
        {
            foreach ( AssemblyName assemblyName in assembly.GetReferencedAssemblies() )
            {
                AddAssembly( Assembly.Load( assemblyName ).Location );
            }
        }
        private void AddEntryAssemblyReferences_()
        {
            Assembly entryAssembly = Assembly.GetEntryAssembly();
            AddAssembly( entryAssembly.Location );
            foreach ( AssemblyName assemblyName in entryAssembly.GetReferencedAssemblies() )
            {
                AddAssembly( Assembly.Load( assemblyName ).Location );
            }
        }
        internal LinqTextQueryRuntime<TSource> CreateRuntimeQuery<TSource>( string queryText ) where TSource : class
        {
            if ( queryText == null ) throw new ArgumentNullException( "queryText" );
            LinqTextQueryRuntime<TSource> runtime = null;
            if ( AddEntryAssemblyReferences )
                AddEntryAssemblyReferences_();
            if ( UsedNamespaces == null )
                runtime = new LinqTextQueryRuntime<TSource>( queryText, UsedAssembliesLocations );
            else
                runtime = new LinqTextQueryRuntime<TSource>( queryText, UsedAssembliesLocations, UsedNamespaces );
            return runtime;
        }

    }
}
